from django.shortcuts import render, redirect
from django.http import request, HttpResponse, HttpResponseRedirect, JsonResponse

from db.models import *
from django.core.paginator import Paginator
import time
from django_redis import get_redis_connection
from django.db import transaction
from utils.login_verify import verify
from utils.pay import AliPay
import json


# 分页展示

def udai_order(request, pindex):
    a = Order.objects.filter(is_delete=0, user_id=request.user)
    b = []
    for i in a:
        b.append(i)
    b.reverse()
    paginator = Paginator(b, 3)
    if pindex == "":  # django中默认返回空值，所以加以判断，并设置默认值为1
        pindex = 1
    else:  # 如果有返回在值，把返回值转为整数型
        pindex = int(pindex)

    page = paginator.page(pindex)

    a1 = a.filter(status=0)
    a2 = a.filter(status=2)
    a3 = a.filter(status=3)
    a4 = a.filter(status=1)
    context = {'message':a, "page": page,'a1':a1,'a2':a2,'a3':a3,'a4':a4}
    return render(request, 'order/udai_order.html', context)




def del_order(request):
    a = request.POST
    # 订单id
    b = a['order_id']
    try:
        c = Order.objects.get(id=b)
    except Order.DoesNotExist:
        content = {'mse': '订单号有误'}
        return HttpResponse(json.dumps(content), content_type='application/json')
    else:
        c.is_delete = 1
        c.save()
        content = {'mse': '删除成功'}
        return HttpResponse(json.dumps(content), content_type='application/json')


@transaction.atomic
def create_order(request):
    """
    创建订单
    :param request:
    :param user:
    :return:
    """
    a = dict(request.POST)
    print(a)

    order_good = a['sku']
    addr = a['addr'][0]
    print(addr)
    address = Address.objects.get(id=addr)
    conn = get_redis_connection("default")

    cart_key = 'cart_%d'%request.user.id
    print(cart_key)

    for i in order_good:
        save_id = transaction.savepoint()

        orders = eval(conn.hget(cart_key, i).decode('utf-8'))

        print(orders)
        good = Goods.objects.get(id = i)

        if good.inventory - int(orders[0]) < 0:
            content = {'message': '库存不足'}
            return HttpResponse(json.dumps(content), content_type='application/json')
        else:

            order_code = str(time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))) + str(time.time()).replace('.','')[-7:]
            Order.objects.create(code=order_code,user=request.user,goods=good,num=int(orders[0]),status=0,address=address)

            good.inventory -=int(orders[0])

            bd = int(good.code[:-1])
            good.code = str(bd + int(orders[0]))
            good.save()
            conn.hdel(cart_key,i)

    return redirect('http://127.0.0.1:8000/order/udai_order/1/')


def ali():
    # 沙箱环境地址：https://openhome.alipay.com/platform/appDaily.htm?tab=info
    app_id = "2016101000656431"
    # POST请求，用于最后的检测
    notify_url = "http://127.0.0.1:8000/order/page2"

    # GET请求，用于页面的跳转展示
    return_url = "http://127.0.0.1:8000/order/page2/"

    merchant_private_key_path = "keys/应用私钥2048.txt"  # app私钥路径
    alipay_public_key_path = "keys/应用公钥2048.txt"  # 支付宝公钥路径
    print(merchant_private_key_path, '*************')
    print(alipay_public_key_path, '2222222222222222')
    alipay = AliPay(
        appid=app_id,
        app_notify_url=notify_url,
        return_url=return_url,
        app_private_key_path=merchant_private_key_path,
        alipay_public_key_path=alipay_public_key_path,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥
        debug=True,  # 默认False,
    )
    return alipay


#跳转到支付界面
def pay(request):
    info = dict(request.POST)
    order_id = info['order_id'][0]
    a = Order.objects.get(id=order_id)
    context = {'message': a}
    return render(request, 'order/udai_shopcart_pay.html', context)


def page1(request):
    if request.method == "GET":
        return render(request, 'order/udai_shopcart_pay.html')
    else:
        money = float(request.POST.get('money'))
        good = request.POST.get('shangping')
        go = Goods.objects.get(name=good)
        print(go.id, 'eeeeeeeeeeeeeeeeeeeee')
        code = Order.objects.get(goods_id=go.id).code

        # print(money,'aaaaaaaaaa')
        # print(request.POST.get('shangping'),'bbbbbbbbbbb')
        alipay = ali()
        # 生成支付的url
        query_params = alipay.direct_pay(
            subject=request.POST.get('shangping'),  # 商品简单描述
            out_trade_no=code,  # 商户订单号
            total_amount=money,  # 交易金额(单位: 元 保留俩位小数)
        )

        pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)

        return redirect(pay_url)


def page2(request):
    alipay = ali()
    if request.method == "POST":
        # 检测是否支付成功
        # 去请求体中获取所有返回的数据：状态/订单号
        from urllib.parse import parse_qs
        body_str = request.body.decode('utf-8')
        post_data = parse_qs(body_str)

        post_dict = {}
        for k, v in post_data.items():
            post_dict[k] = v[0]
        print(post_dict)

        sign = post_dict.pop('sign', None)
        status = alipay.verify(post_dict, sign)
        print('POST验证', status)
        return HttpResponse('POST返回')

    else:
        params = request.GET.dict()
        sign = params.pop('sign', None)
        status = alipay.verify(params, sign)
        print(params, '22222222')
        code = params['out_trade_no']
        print(code, 'code')
        goods = Order.objects.filter(code=code)

        print(goods,'ddddddddddd')
        goods.update(status = 2)
        print('GET验证', status)
        return redirect('http://127.0.0.1:8000/order/udai_order/1/')


def confirm_receipt(request,pk):
    """
    确认收货
    :param request:
    :return:
    """
    a = Order.objects.get(id = pk)
    context = {'message': a}
    return render(request,'order/udai_order_receipted.html',context)

def queren_tiaozhuan(request):
    '''
    确认支付之后跳转页面
    :return:
    '''
    a = request.POST
    print(a)
    b = a['order_id']
    c = Order.objects.get(pk = b)
    c.status = 3
    c.save()
    return redirect('http://127.0.0.1:8000/order/udai_order/1/')

def evaluation(request):
    """
    评价商品
    :param request:
    :return:
    """
    pass
